<template>
  <div class="body">
    <el-row>
      <el-col :xs="24" :sm="24"
        ><div class="page-header">
          <div class="page-title">在线聊天室({{ this.selected }})</div>
          <div v-if="online" class="page-online">在线</div>
          <div v-else class="page-offline">离线</div>
        </div>
        <!-- 显示用户在线信息 -->
        <div class="grid-btn" @click="Grid_btn()">
          <i class="el-icon-s-grid"></i>
        </div>
        <!-- 退出按钮 -->
        <div class="logout-btn" @click="closeWebSocket()">
          <i class="el-icon-switch-button"></i>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <!-- 内容背景 -->
      <el-col :xs="24" :sm="24">
        <div class="bg-content">
          <div class="message-panel">
            <!-- v-html="message" -->
            <div class="message-content" v-html="message"></div>
          </div>
        </div>
      </el-col>
    </el-row>
    <div class="bg-bar">
      <div>
        <el-input
          class="sendMessage"
          v-model="sendMessage"
          placeholder="请输入消息"
          maxlength="120"
          show-word-limit
        ></el-input>
        <span class="emot-btn">
          <i @click="show_emot()" class="fa fa-smile-o"></i>
          <div v-if="show" class="chat-emotion">
            <ul class="emot-list clearfix">
              <li v-for="(item, index) in emot_list" :key="index">
                <img
                  @click="select_emot(item.id)"
                  v-bind:alt="item.id"
                  v-bind:src="item.src"
                />
              </li>
            </ul>
          </div>
        </span>

        <el-button
          class="el-button el-button--primary is-circle send-btn"
          @click="Send()"
        >
          <i class="el-icon-s-promotion"></i>
        </el-button>
      </div>
    </div>
    <!-- 用户在线人数列表抽屉 -->
    <el-drawer
      :title="'在线用户' + onlineCounts + '人'"
      :visible.sync="drawer"
      :direction="direction"
      size="50%"
    >
      <div class="user-list">
        <ul v-for="(item, index) in onLineUser" :key="index">
          <li>
            <a href="javascript:void(0);" @click="selectUser($event)">{{
              item
            }}</a>
          </li>
        </ul>
      </div>
    </el-drawer>
    <!-- 用户登录界面 -->
    <el-dialog
      title="请登录"
      :visible.sync="loginDialogVisible"
      :before-close="handleClose"
      width="90%"
    >
      <div>
        <el-form label-width="60px">
          <el-form-item label="用户名">
            <el-input v-model="username" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="Open()">登录服务</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "NewMobileView",
  data() {
    return {
      username: "",
      online: false,
      loginDialogVisible: true, //默认登录页面始终显示，登录成功后设置为false
      onLineUser: ["--所有人--"],
      onlineCounts: 0,
      webSocket: null,
      heartCheck: null,
      selected: "--所有人--",
      message: "",
      sendMessage: "",
      show: false, //表情包按钮显示
      emot_num: 75,
      emot_list: [],
      imgsrc: "../assets/emot/$1.gif",
      defaultStyle: {
        height: window.innerHeight - 76 - 65 + "px", //空白背景动态高度
      },
      drawer: false,
      direction: "ltr",
    };
  },
  watch: {
    // 监听screenHeight从而改变table的高度
    screenHeight(val) {
      this.screenHeight = val;
      this.defaultStyle.height = this.screenHeight - 76 - 65;
    },
  },
  mounted() {
    this.defaultStyle.height = this.screenHeight - 76 - 65;
    this.init_emot();
  },
  methods: {
    init() {
      const _this = this;
      //console.log(this.username);
      _this.webSocket = new WebSocket(
        "wss://www.archeage.top/chatroomserver/websocket/" + this.username
      );

      //连通之后的回调事件
      _this.webSocket.onopen = function () {
        _this.setMessageInnerHTML(
          "<b>系统通知：您已成功进入聊天室，请自觉维护聊天室的正常秩序！</b>"
        );

        //设置心跳机制
        _this.heartCheck = setInterval(function () {
          _this.webSocket.send("HeartBeat");
        }, 50000); // 发送心跳消息的时间间隔，单位毫秒
      };

      //接收后台服务端的消息
      _this.webSocket.onmessage = function (evt) {
        clearInterval(_this.heartCheck);
        _this.heartCheck = setInterval(function () {
          _this.webSocket.send("HeartBeat");
        }, 5000);
        let received_msg = evt.data;
        console.log("数据已接收:" + received_msg);
        let obj = JSON.parse(received_msg);
        console.log("可以解析成json:" + obj.messageType);
        //1代表上线 2代表下线 3代表在线名单 4代表普通消息
        if (obj.messageType == 1) {
          //有新用户上线
          //把名称放入到selection当中供选择
          let onlineName = obj.username;
          let option = onlineName;
          _this.onLineUser.push(option);
          _this.setMessageInnerHTML(
            "<b>系统通知：" + onlineName + "上线了</b>"
          );
          _this.onlineCounts++;
        } else if (obj.messageType == 2) {
          //有用户下线，将用户移除
          _this.onLineUser = ["--所有人--"];
          let onlineName = obj.onlineUsers;
          let offlineName = obj.username;
          for (let i = 0; i < onlineName.length; i++) {
            if (!(onlineName[i] == _this.username)) {
              _this.onLineUser.push(onlineName[i]);
            }
          }

          _this.onlineCounts--;
          _this.setMessageInnerHTML(
            "<b>系统通知：" + offlineName + "下线了</b>"
          );
        } else if (obj.messageType == 3) {
          //用户上线接收在线数据
          _this.onLineUser = ["--所有人--"];
          let onlineName = obj.onlineUsers;
          for (let i = 0; i < onlineName.length; i++) {
            if (!(onlineName[i] == _this.username)) {
              //如果在线用户不等于自己，将用户加入列表中
              _this.onLineUser.push(onlineName[i]);
            }
          }
          //更新在线人数
          _this.onlineCounts = onlineName.length;

          console.log("获取了在线的名单" + onlineName.toString());
        } else {
          if (obj.tousername == _this.username) {
            _this.setMessageInnerHTML(
              obj.fromusername + "对你说：" + _this.replace_em(obj.textMessage)
            );
          } else {
            if (obj.fromusername == _this.username) {
              _this.ImsetMessageInnerHTML(
                obj.fromusername +
                  "对" +
                  obj.tousername +
                  "说：" +
                  _this.replace_em(obj.textMessage)
              );
            } else {
              _this.setMessageInnerHTML(
                obj.fromusername +
                  "对" +
                  obj.tousername +
                  "说：" +
                  _this.replace_em(obj.textMessage)
              );
            }
          }
          _this.scrollToBottom();
        }
      };

      //连接关闭的回调事件
      _this.webSocket.onclose = function () {
        //console.log("连接已关闭...");
        _this.setMessageInnerHTML("退出聊天室，连接已经关闭....");
        _this.loginDialogVisible = true;
        _this.online = false;
        //清空列表
        _this.onLineUser = [];
        _this.onLineUser.push("--所有人--");
        clearInterval(_this.heartCheck); //清除定时器
      };
    },
    Open() {
      if (this.username.trim() == "") {
        this.$message.error("昵称不能为空");
        this.username = "";
        return;
      } else {
        //console.log(this.username);
        this.loginDialogVisible = false;
        this.init();
        this.online = true;
      }
    },
    setMessageInnerHTML(innerHTML) {
      this.message += this.anotherMessage(innerHTML);
    },
    ImsetMessageInnerHTML(innerHTML) {
      this.message += this.currentMessage(innerHTML);
    },
    closeWebSocket() {
      //直接关闭websocket的连接
      this.webSocket.close();
      clearInterval(this.heartCheck); //清除定时器
      this.loginDialogVisible = true;
      this.$message({
        message: "已退出聊天室",
        type: "success",
      });
      this.online = false;
    },
    Send() {
      const _this = this;
      if (_this.sendMessage.trim() == "" || _this.sendMessage.trim() == null) {
        this.$message.error("输入内容不能为空！");
        return;
      }

      let selectText = this.selected;
      //console.log("发送方法");
      if (selectText == "--所有人--") {
        selectText = "All";
      } else {
        //console.log("私信中");
        //_this.message = _this.message + _this.currentMessage(_this.sendMessage);
        _this.ImsetMessageInnerHTML(
          "你" + "对" + selectText + "说：" + _this.replace_em(this.sendMessage)
        );
      }
      let message = {
        message: this.sendMessage.trim(),
        username: this.username,
        to: selectText,
      };
      _this.webSocket.send(JSON.stringify(message));
      _this.sendMessage = "";
      _this.scrollToBottom();
    },
    //定位消息在最后一行
    scrollToBottom() {
      this.$nextTick(() => {
        var container = this.$el.querySelector(".message-panel");
        container.scrollTop = container.scrollHeight;
      });
    },
    Grid_btn() {
      console.log("grid");
      this.drawer = true;
    },
    // 点击选择用户
    selectUser(e) {
      //console.log(e.target.innerHTML);
      this.selected = e.target.innerHTML;
      this.drawer = false;
      //发送通知消息
      const h = this.$createElement;

      this.$notify({
        title: "消息提示",
        message: h(
          "i",
          { style: "color: #5ce228" },
          "您正在与" + this.selected + "进行通话。"
        ),
      });
    },
    //封装两个消息样式
    currentMessage(msg) {
      let str = '<div class="message">';
      str += '<div class="send-style">';
      str += msg;
      str += "</div>";
      str += "</div>";
      return str;
    },
    anotherMessage(msg) {
      let str = '<div class="message">';
      str += '<div class="others-style">';
      str += msg;
      str += "</div>";
      str += "</div>";
      return str;
    },
    //表情包
    init_emot() {
      //初始化方法
      var _this = this;
      //默认生成表情列表
      for (let i = 1; i <= _this.emot_num; i++) {
        var emot = new Object();
        emot.id = i;
        emot.src = require("@/assets/emot/" + i + ".gif");
        _this.emot_list.push(emot);
      }
    },
    show_emot() {
      this.show = !this.show;
    },
    select_emot(e) {
      //根据点击表情id生成快捷文字
      var el = e;
      var em_text = "[em_" + el + "]";
      //关闭表情选择器并将内容赋值到input表签内
      this.show = false;
      //console.log("test:"+em_text)
      //console.log(this.replace_em(testdata))
      this.sendMessage += em_text;
    },
    //查看显示结果
    replace_em(str) {
      str = str.replace(/\</g, "&lt;");

      str = str.replace(/\>/g, "&gt;");

      str = str.replace(/\n/g, "<br/>");

      str = str.replace(
        /\[em_([0-9]*)\]/g,
        '<img src="emot/$1.gif" border="0" />'
      );

      return str;
    },
    handleClose() {
      this.$message.error("请登录");
      this.loginDialogVisible = true;
    },
  },
};
</script>
<style scoped>
.body {
  background: #FFFFFF;
  height: 100vh;
}

.page-header {
  position: fixed;
  margin: 20px auto;
  text-align: center;
  display: block;
  position: relative;
}
.page-title {
  font-size: 16px;
  line-height: 20px;
  font-weight: 800;
  color: #000;
  overflow: hidden;
}
.page-online {
  font-size: 12px;
  color: #5ce228;
}

.page-offline {
  font-size: 12px;
  color: #ee2424;
}

.grid-btn > i {
  font-size: 20px;
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 99;
  background: #fff;
  padding: 10px;
}

.logout-btn {
  font-size: 20px;
  position: absolute;
  right: 30px;
  top: 25px;
  z-index: 99;
  color: #ff0000;
}

.user-list {
  text-align: center;
}

.user-list a {
  color: #000;
  font-size: 14px;
}

/* 中间消息 */
.bg-content {
  background: #fff;
  border-radius: 20px;
  height: 78vh;
}

.message-panel {
  overflow-y: auto;
  height: 78vh;
}

.message-content {
  color: #000;
  margin: 10px 10px;
  font-size: 16px;
}

/* 消息外侧样式 */
.message::after {
  margin-bottom: 8px;
  content: ".";
  display: block;
  visibility: hidden;
  height: 0;
  clear: both;
  overflow: hidden;
}

.chat-emotion {
  position: absolute;
  z-index: 999;
  left: 10px;
  bottom: 70px;
  width: 345px;
  height: 185px;
  padding: 5px;
  background: #fff;
  border: 1px solid #999999;
}

.emot-btn i {
  font-size: 24px;
}

.emot-btn .emot-list li {
  float: left;
}

.emot-btn .emot-list li img {
  cursor: pointer;
  border: 1px #fff solid;
}

.emot-btn .emot-list li img:hover {
  border: 1px #0066cc solid;
}

/* 发信样式 */
.send-style {
  max-width: 80%;
  text-align: right;
  background: #caeffc;
  float: right;
  padding: 10px 20px;
  border-radius: 8px;
}

.others-style {
  max-width: 80%;
  background: #ccf7c4;
  float: left;
  padding: 10px 20px;
  border-radius: 8px;
}

.bg-bar {
  height: 55px;
  text-align: center;
  padding: 10px 10%;
  position: fixed;
  bottom:0;
}

.sendMessage {
  width: 65%;
}

.sendMessage .el-input__inner {
  background: #f4f7f2;
}

.emot-btn {
  font-size: 20px;
  cursor: pointer;
  color: #495057;
  margin-left: 10px;
}

.sendMessage input {
  border-radius: 25px;
}

.el-button.is-circle {
  border-radius: 50%;
  padding: 10px;
}

.send-btn {
  margin-left: 20px;
  font-size: 20px;
}
</style>